import Api from '@/api'
import useUserStore from '@/store/user.ts'
import type {ResMenuList, ResUserInfo} from '@/api/interface'
import Layout from '@/layouts/index.vue'
import router, {addStaticRoutes} from '@/router/index.ts'
import useRouteStore from '@/store/route.ts'

const modules = import.meta.glob('@/views/**/*.vue')

// 获取用户信息
export const getUserInfo = async () => {
	return await new Promise((resolve, reject) => {
		try {
			const userStore = useUserStore()
			const routeStore = useRouteStore()
			Api.getUserInfo().then((res: ResUserInfo) => {
				if (res.code !== 200) return
				userStore.setUserId(res.data.userId)
				userStore.setUserName(res.data.nickName)
				userStore.setRoles(res.data.roles)
				userStore.setAvatar(res.data.avatar)
				userStore.setPermissions(res.data.permissions)
				Api.getRouters().then(async (r: ResMenuList[]) => {
					let result = r as any
					const res: ResMenuList[] = [...result.data, ...addStaticRoutes]
					const sData = JSON.parse(JSON.stringify(res))
					const rData = JSON.parse(JSON.stringify(res))
					const sidebarRoutes = filterAsyncRouter(sData)
					const rewriteRoutes = filterAsyncRouter(rData)
					routeStore.setMenuList(sidebarRoutes)
					rewriteRoutes.push({
						path: '/',
						redirect: getChildren(sidebarRoutes, '')
						//redirect: rewriteRoutes[0].path + (rewriteRoutes[0]?.children?.length ? ('/' + rewriteRoutes[0]?.children[0]?.path) : '')
					})
					rewriteRoutes.forEach((item: any) => {
						router.addRoute(item)
					})
					router.addRoute({
						path: '/:pathMatch(.*)',
						redirect: '/404'
					})
					resolve(rewriteRoutes)
				}).catch((err: any) => {
					reject(err)
				})
			})
		} catch (e) {
			reject(e)
		}
	})
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: ResMenuList[]) {
	return asyncRouterMap.filter(route => {
		if (route.component) {
			if (route.component === 'Layout') {
				route.component = Layout
				route.path = '/' + route.path
				route.menuType = 'P'
				//if (route.children?.length) {
				//	route.redirect = route.path + '/' + route.children[0].path
				//}
			} else {
				route.component = modules['/src/views/' + route.component + '.vue']
				route.menuType = 'M'
			}
			route.path = route.query ? route.path + '/:' + route.query : route.path
		}
		if (route.children?.length) {
			route.children = filterAsyncRouter(route.children)
		} else {
			delete route.children
			delete route.redirect
		}
		return true
	})
}

const getChildren = (arr: Array<any>, str: string) => {
	str = str + (arr[0].path[0] === '/' ? arr[0].path : '/' + arr[0].path)
	if (arr[0].children && arr[0].children.length) {
		return getChildren(arr[0].children, str)
	}
	return str
}
